import godebug from '../godebug'
export default (function() {
    // _log('default XMLHttpRequest')
    var XHR = XMLHttpRequest.prototype;
    if (!XHR) return;
    let open = XHR.open;
    // var onreadystatechange = XHR.onreadystatechange;

    let type,
        url,
        startTime, endTime;
    XHR.open = function(method, reqUrl) {
        type = method;
        this.reqUrl = reqUrl;
      //  _log(this)
        godebug.emit('open', [type, reqUrl]);
        try {
            open.apply(this, arguments);
        } catch (error) {
            _log('open****************')
            _log(error);
        }

    }
    let send = XHR.send;
    XHR.send = function(a, b) {
      //  _log(this)
        let _this = this,
            onreadystatechange = _this.onreadystatechange;
        this.addEventListener && this.addEventListener('readystatechange', function() {
            if (_this.readyState == 4) {
                let data = {
                     reqUrl:this.reqUrl
                };
                godebug.emit('httpComplete',data)
                
                //_log(this)
                switch (_this.status) {
                    case 200:
                        godebug.emit('httpDone',data);
                        break;
                    case 404:
                        godebug.emit('notFound',data);
                        break;
                    case 500:
                        godebug.emit('httpError',data);
                        break;
                    default:
                        break;
                }               
            }
      })
        try {
            send.apply(this,arguments);
        } catch (error) {
            _log('****************')
            _log(error);
        }
       // _log(this.responseURL)
        godebug.emit('send', {
            reqUrl:this.reqUrl
        });
    }
}())